<template>
  <!-- 溯源列表页面主容器 -->
  <div class="traceable-list">
    <!-- 页面头部：标题和新增按钮 -->
    <div class="page-header">
      <h2>产品溯源管理</h2>
    </div>

    <!-- 搜索区域：用于筛选溯源记录 -->
    <div class="search-area">
      <el-form :inline="true" :model="page" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="page.GoodsName" placeholder="请输入产品名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="批次号">
          <el-input v-model="page.Batch" placeholder="请输入批次号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="GetGoodsTraceable">查询</el-button>
          <el-button type="info" @click="Cealer">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域：展示溯源记录列表 -->
    <div class="search-area">
      <el-button type="success" @click="Addtraceable">+新增</el-button>
      <el-button type="danger" @click="batchDelete" :disabled="selectedRows.length === 0">-删除</el-button>

      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
        ref="tableRef">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="goodsName" label="产品名称" min-width="150"></el-table-column>
        <el-table-column prop="batch" label="生产批次号" width="120"></el-table-column>
        <el-table-column prop="expiration" label="保质期(天)" width="120"></el-table-column>
        <el-table-column prop="permit" label="生产许可证号" width="150"></el-table-column>
        <el-table-column prop="companies" label="生产企业" min-width="210"></el-table-column>
        <el-table-column prop="perfect" label="信息完善度" width="120">
           <template #default="scope">
               <el-progress v-if="scope.row.perfect>=100" :text-inside="true" status="success" :stroke-width="20" :percentage="scope.row.perfect" />
                <el-progress v-if="scope.row.perfect<100" :text-inside="true" status="exception" :stroke-width="20" :percentage="scope.row.perfect" />
           </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{moment(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss')}}
          </template>
        </el-table-column>
        <el-table-column prop="creater" label="创建人" width="120"></el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="160">
           <template #default="scope">
            {{scope.row.updateTime ? moment(scope.row.updateTime).format('YYYY-MM-DD HH:mm:ss'):''}}
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDetail(scope.row.id)">查看</el-button>
            <el-button type="success" size="small" @click="editTraceable(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteTraceable(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageindex"
          v-model:page-size="page.pagesize"
          :page-sizes="[15, 16, 17, 18]"
          layout="slot, sizes, prev, pager, next, jumper"
          :total="page.TotalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          prev-text="上一页"
          next-text="下一页"
        >共{{page.TotalCount}}条 当前第{{page.pageindex}}页/共{{page.TotalPage}}页</el-pagination>
      </div>
    </div>
<!-- 溯源基本信息新增 -->
    <el-dialog v-model="dialogVisible" title="基本信息新增" width="500">
      <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          
          <el-form-item label="商品名称" prop="goodsId">
            <el-select v-model="ruleForm.goodsId" placeholder="请选择">
              <el-option v-for="item in goodsData" :label="item.goodsName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="生产批次" prop="batch">
            <el-input v-model="ruleForm.batch" />
          </el-form-item>
          <el-form-item label="保质期" prop="expiration">
            <el-input v-model="ruleForm.expiration" />
          </el-form-item>
          <el-form-item label="生产许可证" prop="permit">
            <el-input v-model="ruleForm.permit" />
          </el-form-item>
          <el-form-item label="生产企业" prop="companies">
            <el-input v-model="ruleForm.companies" />
          </el-form-item>
           <el-form-item label="封面图" prop="cover">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:5263/api/FileUploadFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              保存
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>
    <!-- 溯源基本信息编辑 -->
    <el-dialog v-model="UpdialogVisible" title="基本信息编辑" width="500">
      <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          
          <el-form-item label="商品名称" prop="goodsId">
            <el-select v-model="ruleForm.goodsId" placeholder="请选择">
              <el-option v-for="item in goodsData" :label="item.goodsName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="生产批次" prop="batch">
            <el-input v-model="ruleForm.batch" />
          </el-form-item>
          <el-form-item label="保质期" prop="expiration">
            <el-input v-model="ruleForm.expiration" />
          </el-form-item>
          <el-form-item label="生产许可证" prop="permit">
            <el-input v-model="ruleForm.permit" />
          </el-form-item>
          <el-form-item label="生产企业" prop="companies">
            <el-input v-model="ruleForm.companies" />
          </el-form-item>
           <el-form-item label="封面图" prop="cover">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:5253/api/GoodsUpImg"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="ruleForm.cover" :src="ruleForm.cover" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="UpsubmitForm(ruleFormRef)">
              更新
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          </el-form-item>
        </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
import {App} from '@/http/interceptors'
import moment from 'moment'
import {ElMessage, ElMessageBox, type FormInstance, type FormRules} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'


//#region  商品溯源基本信息查询

const tableData=ref([])

const page=reactive({
  pageindex:1,
  pagesize:15,
  TotalCount:0,
  TotalPage:0,
  GoodsName:"",
  Batch:""
})

onMounted(()=>{
GetGoodsTraceable();
})

const GetGoodsTraceable=()=>{
  App.get("/api/GoodsGetTraceablelist",{params:page}).then(res=>{
    tableData.value=res.data.pagData
    page.TotalCount=res.data.totalCount
    page.TotalPage=res.data.totalPage
  })
}

//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.pagesize=val
  GetGoodsTraceable();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.pageindex=val
  GetGoodsTraceable();
}

//重置
const Cealer=()=>{
page.Batch="",
page.GoodsName=""
GetGoodsTraceable();
}

//#endregion

//#region  商品下拉框
const goodsData=ref<any>([])
onMounted(()=>{
  GetGoods();
})

const GetGoods=()=>{
  App.get("/api/GoodsGetGoods",{}).then(res=>{
    goodsData.value=res.data.data
  })
}

//#endregion

//#region  商品溯源新增
const dialogVisible=ref(false)
// 当前日期年月日的数字字符串，格式：yyyyMMdd
const DayNo = ref(moment().format('YYYYMMDD'))
const Addtraceable=()=>{
  dialogVisible.value=true
  ruleForm.goodsId='',
  ruleForm.batch=DayNo.value,
  ruleForm.expiration=null,
  ruleForm.companies="",
  ruleForm.perfect=0,
  ruleForm.permit="",
  ruleForm.cover=""
}


const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
 "goodsId": '',
  "batch": "",
  "expiration":null,
  "permit": "",
  "companies": "",
  "perfect": 0,
  "cover": ""
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  goodsId: [
    { required: true, message: '商品名称必选', trigger: 'blur' },
  ],
  batch: [
    { required: true, message: '生产批次不能为空', trigger: 'blur' },
  ],
  expiration: [
    { required: true, message: '保质期不能为空', trigger: 'blur' },
  ],
  permit: [
    { required: true, message: '生产许可证不能为空', trigger: 'blur' },
  ],
  companies: [
    { required: true, message: '生产企业不能为空', trigger: 'blur' },
  ],
  cover: [
    { required: true, message: '封面图不能为空', trigger: 'blur' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      App.post("/api/GoodsCreateGoodsTraceable",ruleForm).then(res=>{
        if(res.data.code==200)
        {
          dialogVisible.value=false
          ruleForm.goodsId='',
          ruleForm.batch="",
          ruleForm.companies="",
          ruleForm.expiration=null,
          ruleForm.perfect=0,
          ruleForm.permit="",
          ruleForm.cover=""
          GetGoodsTraceable();
          ElMessage.success(res.data.message)
        }
        else{
          ElMessage.error(res.data.message)
        }
      })
      
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

//======================上传图片=========================
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.cover=response.data
}

//#endregion

//#region  查看商品溯源详情
const viewDetail = (id: any) => {
  router.push({
    path: '/traceabledetail',
    query: {
      Id:id,
      mode: 'view'
    }
  })
}
//#endregion


//#region   编辑商品信息
const UpdialogVisible=ref(false)

const editTraceable = (row: any) => {
   UpdialogVisible.value=true
   Object.assign(ruleForm,row)
}


const UpsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      App.put("/api/GoodsUpdateGoodsTraceable",ruleForm).then(res=>{
        if(res.data.code==200)
        {
          UpdialogVisible.value=false
          ruleForm.goodsId='',
          ruleForm.batch="",
          ruleForm.companies="",
          ruleForm.expiration=null,
          ruleForm.perfect=0,
          ruleForm.permit="",
          ruleForm.cover=""
          GetGoodsTraceable();
          ElMessage.success(res.data.message)
        }
        else{
          ElMessage.error(res.data.message)
        }
      })
      
    } else {
      console.log('error submit!', fields)
    }
  })
}
//#endregion


//#region  删除数据
const deleteTraceable = (id: any) => {
  ElMessageBox.confirm(
    `确定要删除本商品的溯源记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 调用删除API - 将单个ID包装成数组，与批量删除使用相同的格式
    App.post("/api/GoodsDeleteGoodsTraceable", { Id: [id] }).then(res => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        // 刷新数据
        GetGoodsTraceable()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    }).catch(error => {
      console.error('删除出错：', error)
      ElMessage.error('删除过程中发生错误')
    })
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除操作')
  })
}
//#endregion

//#region  全选和反选功能
const tableRef = ref()//全选
const selectedRows = ref<any[]>([])//所选择的行

// 选择变化事件处理
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 全选功能
const handleSelectAll = () => {
  // 循环选中表格中的所有行
  tableData.value.forEach(row => {
    tableRef.value.toggleRowSelection(row, true)
  })
}

// 反选功能 - 简化版
const handleDeselectAll = () => {
  // 获取表格中所有行
  tableData.value.forEach(row => {
    // 直接切换每一行的选择状态
    tableRef.value.toggleRowSelection(row)
  })
}
//#endregion

//#region  批量删除
const batchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length}个溯源商品吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 获取所有选中行的ID
    const ids = selectedRows.value.map(row => row.id)
    console.log("id集合", ids)
    
    App.post("/api/GoodsDeleteGoodsTraceable", { Id: ids }).then(res => {
        if (res.data.code === 200) {
          ElMessage.success(`已删除${selectedRows.value.length}个溯源商品`)
          // 刷新数据
          GetGoodsTraceable();
          // 清空选择
          selectedRows.value = []
        } else {
          ElMessage.error(res.data.message || '批量删除失败')
        }
     })
  }).catch(() => {
    // 用户取消删除操作
    ElMessage.info('已取消删除操作')
  })
}
//#endregion

</script>


<!-- 图片 -->
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>




<style scoped>
/* 溯源列表页面主容器样式 */
.traceable-list {
  padding: 20px;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 搜索区域样式 */
.search-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格区域样式 */
.table-area {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>